import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_lang/lang_index.dart';
import 'package:oktoast/oktoast.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:flutter/services.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:permission_handler/permission_handler.dart';
import 'dart:ui' as ui;
import 'dart:convert';
import 'package:convert/convert.dart';
import 'package:crypto/crypto.dart';
import 'package:wallet_home/model/wallet_list_model.dart';
import 'package:wallet_home/tools/theme_utils.dart';

import '../module_config.dart';


class CollectionQRCodeView extends StatefulWidget {
  @override
  _CollectionQRCodeViewState createState() => _CollectionQRCodeViewState();
}

class _CollectionQRCodeViewState extends State<CollectionQRCodeView> {
  GlobalKey globalKey = GlobalKey();

  var _alignment = Alignment(0.05,10);
  // bool upDrag = false;
  CoinsBean _bean;

  @override
  void initState() {
    super.initState();
    Future.delayed(Duration(milliseconds:10),(){
      _alignment = Alignment(0.05,0.2);
      setState(() {

      });
    });
  }

  @override
  Widget build(BuildContext context) {
    _bean = ModalRoute.of(context).settings.arguments;
    return Scaffold(
      body: GestureDetector(
        onTap: (){
          Navigator.pop(context);
        },
        child: Container(
          width: MediaQuery.of(context).size.width,
          height: MediaQuery.of(context).size.height,
          color: Colors.grey[900],
          child: RepaintBoundary(
            key: globalKey,
            child: AnimatedAlign(
              alignment: _alignment,
              duration: Duration(milliseconds: 300),
              child: Container(
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.all(Radius.circular(15.0)),
                      color: ThemeUtils.getThemeColor(
                          context:context,
                          brightnessColor: Colors.white,
                          darkColor: Colors.white30
                      )
                  ),
                  width: 280,
                  height: 440,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      _coinAddress(),
                      _longPressNotice(),
                      _qrCode(),
                      _keyAddress(),
                      _copyBtn(),
                      _bottomNotice(),
                    ],
                  )
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _coinAddress(){
    return Container(
        margin: EdgeInsets.only(top: 15),
        child: Text("${_bean.title} ${WXLang.$t("search_address",package: ModuleConfig.moduleName)}",style: TextStyle(fontSize: 16,color: Colors.black),)
    );
  }

  Widget _longPressNotice(){
    return Container(
        margin: EdgeInsets.only(top: 10,bottom: 5),
        child: Text(
          "${WXLang.$t("search_long_press_save",package: ModuleConfig.moduleName)}",
          style: TextStyle(fontSize: 12,color: Colors.orange),
        )
    );
  }

  Widget _qrCode(){
    return GestureDetector(
      child: QrImage(
          backgroundColor:Color(0x00000000),
          foregroundColor: Colors.blue,
          data:_bean.address,
          size: 200,
      ),
      onLongPress: () {
        _savePhotos(Platform.isIOS ? Permission.photos : Permission.storage);
      },
    );
  }

  Widget _keyAddress(){
    return Container(
        width: 184,
        margin: EdgeInsets.only(top: 5,bottom: 5),
        child: Text(
          _bean.address.toUpperCase(),
          style: TextStyle(
              fontSize: 14,
            color: ThemeUtils.getThemeColor(
                context:context,
                brightnessColor: Color(0xff444444),
                darkColor: Colors.black
            ),
          ),
        )
    );
  }

  Widget _copyBtn(){
    return Container(
      width: 184,
      height: 44,
      margin: EdgeInsets.only(top: 8),
      child: FlatButton(
        onPressed: (){
          Clipboard.setData(ClipboardData(text: _bean.address));
        },
        shape:RoundedRectangleBorder(borderRadius:BorderRadius.all(Radius.circular(5.0)) ) ,
//        color: Color(0xFFbf8000),
        color: ThemeUtils.getThemeColor(
            context: context,
          brightnessColor: Color(0xFFbf8000),
          darkColor: Colors.white38
        ),
        child: Text("${WXLang.$t("search_copy",package: ModuleConfig.moduleName)}",style: TextStyle(fontSize: 14,color: Colors.white),),
      ),
    );
  }

  Widget _bottomNotice(){
    return Container(
        width: 240,
        margin: EdgeInsets.only(top: 15),
        child: Text(
          "${WXLang.$t("search_collection_notice_before",package: ModuleConfig.moduleName)} ${_bean.title} \n${WXLang.$t("search_collection_notice_after",package: ModuleConfig.moduleName)}",
          style: TextStyle(
              fontSize: 12,
              color: ThemeUtils.getThemeColor(
                  context: context,
                brightnessColor: Color(0xffc00000),
                darkColor: Colors.white38
              )
          ),
          textAlign: TextAlign.center,
        )
    );
  }

  _savePhotos(Permission permission){
    permission.status.then((value) async {
      if(value == PermissionStatus.granted){
        _saveImageToPhotos();
      } else {
        permission.request().then((value){
          if(value == PermissionStatus.granted){
            _saveImageToPhotos();
          }
        });
      }
    });
  }

  _saveImageToPhotos() async {
    BuildContext buildContext = globalKey.currentContext;
    if (null != buildContext){
      RenderRepaintBoundary boundary = buildContext.findRenderObject();
      ui.Image image = await boundary.toImage();
      ByteData byteData = await image.toByteData(format: ui.ImageByteFormat.png);
      final result = await ImageGallerySaver.saveImage(byteData.buffer.asUint8List(),quality: 100);
      if (result != null){
        showToast("${WXLang.$t("search_save_toast",package: ModuleConfig.moduleName)}",
            position: ToastPosition(),
            duration: Duration(milliseconds: 2000), dismissOtherToast: true);
      }
    }
  }
}
